package com.cat.slidingWindow;

import java.util.HashSet;
import java.util.Map;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-sum-of-distinct-subarrays-with-length-k/description/
 * @create 2025/9/16 10:18
 * @since JDK17
 */

public class Solution28 {
    HashSet<Integer> set = new HashSet<>();

    public long maximumSubarraySum(int[] nums, int k) {
        long sum = 0, ans = 0;
        int n = nums.length;
        for (int l = 0, r = 0; r < n; ) {
            if (!set.contains(nums[r])) {   // 该数字不在哈希表中
                sum += nums[r];
                set.add(nums[r++]);
            } else {    // 必须删除前面的
                sum -= nums[l];
                set.remove(nums[l++]);
            }

            if (r - l == k) {
                ans = Math.max(ans, sum);
                sum -= nums[l];
                set.remove(nums[l++]);
            }
        }

        return ans;
    }
}
